<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import bydmService from '@/api/bydm'
import pinyin from 'pinyin-match'
const columns = [
  {
    title: '分类代码名称',
    dataIndex: 'mc',
  },
  {
    title: '分类代码',
    dataIndex: 'dm',
  },
  {
    title: '说明',
    dataIndex: 'sm',
  },
]
const visible = ref(false)
const visibleTitle = ref('添加分类代码')
const replaceFields = {
  children: 'children',
  label: 'lbmc',
}
const selectTreeNode = ref('')
const gData = ref<any[]>([])
const gData1 = ref<any[]>([])
const nodeMessege = ref<any>({})
const tableNodeMessege = ref<any>({})
const tableLists = ref<any[]>([])
const tableLists1 = ref([])
const addForm = ref<any>({}) //左边的数据
const addfldmlbDia = ref(false)
const changefldmlbDia = ref(false)
const fldmlbTitle = ref('添加分类代码类别')
const selectedRows = ref<any[]>([]) //table选中节点
const addfldmDiaForm = ref({
  dm: '',
  mc: '',
  lbbm: '',
  xh: '',
  sm: '',
  fdm: '',
})
const chanefldmDiaForm = ref({
  dm: '',
  mc: '',
  lbbm: '',
  xh: '',
  sm: '',
  fdm: '',
  fjdm: undefined,
})
const flag = ref(false)
const loading = ref(false)
// 遍历增加字段
const diGui = (arr: any) => {
  for (const item of arr) {
    item.slots = {}
    item.slots.icon = item.level + ''
    if (item.children && item.children.length > 0) {
      diGui(item.children)
    }
  }
  return arr
}
const serchMenuLeft = () => {
  bydmService.queryLeftMenu({}).then((res) => {
    gData.value = diGui(res.data)
    gData1.value = JSON.parse(JSON.stringify(gData.value)) //用于筛选
    selectTreeNode.value = res.data[0].lbbm //设置默认选中值
    nodeMessege.value = res.data[0] //节点信息
    queryTable() //查询表格
  })
}
// 点击的是第几级
const treeSelect = (data: any) => {
  selectTreeNode.value = data.lbbm
  nodeMessege.value = data
  if (nodeMessege.value.level === 1) {
    tableLists.value = []
    return
  }
  queryTable()
}
const queryTable = () => {
  loading.value = true
  const data = {
    lbbm: nodeMessege.value.lbbm,
  }
  bydmService.queryLbTable(data).then((res: any) => {
    tableLists.value = res.data
    tableLists1.value = res.data //临时保存一个值用于筛选
    loading.value = false
  })
}
const addfldmlbBtn = () => {
  // 左边的
  addfldmlbDia.value = true
  fldmlbTitle.value = '添加分类代码类别'
  addForm.value = {}
}
// 左边的 添加 修改 确定按钮
const addfldm = async () => {
  if (!(addForm.value.dmsslb && addForm.value.lbbm && addForm.value.lbmc)) {
    ElMessage.warning('请完善信息')
    return
  }

  if (addForm.value.lbbm.length !== 4) {
    ElMessage.error('类别编码只能是4位数')
    return
  }

  if (fldmlbTitle.value === '添加分类代码类别') {
    const res: any = await bydmService.checkLbbm({
      lbbm: addForm.value.lbbm,
    })

    if (res.data.stats) {
      bydmService.addFldmlb({ ...addForm.value }).then(() => {
        ElMessage.success('添加成功')
        addfldmlbDia.value = false
        serchMenuLeft()
      })
    } else {
      ElMessage.error(res.data.msg)
    }
  }

  if (fldmlbTitle.value === '修改分类代码类别') {
    bydmService.changeSingNode({ ...addForm.value }).then(() => {
      ElMessage.success('修改成功')
      addfldmlbDia.value = false
      serchMenuLeft()
    })
  }
}

// 编辑按钮
const onEdit = () => {
  if (!nodeMessege.value.lbbm) {
    ElMessage.warning('请选择节点进行编辑')
    return
  }
  if (nodeMessege.value.level === 1) {
    ElMessage.warning('父节点不能点击编辑')
    return
  }
  fldmlbTitle.value = '修改分类代码类别'
  addfldmlbDia.value = true
  bydmService.serchSingNode({ lbbm: nodeMessege.value.lbbm }).then((res) => {
    addForm.value = res.data
  })
}

// 删除按钮
const delet = () => {
  if (nodeMessege.value.level === 1) {
    ElMessage.warning('父分类不能点击删除')
    return
  }
  bydmService.deletFldmlb({ lbbm: nodeMessege.value.lbbm }).then(() => {
    ElMessage.success('删除成功')
    serchMenuLeft()
  })
}

//右边的上的添加按钮
const add = () => {
  if (nodeMessege.value.level === 1) {
    ElMessage.warning('父节点不能点击编辑')
    return
  }
  visibleTitle.value = '添加分类代码'
  visible.value = true
  addfldmDiaForm.value.lbbm = nodeMessege.value.lbbm
}
// 添加子代码
const addChildDm = () => {
  if (selectedRows.value.length <= 0) {
    ElMessage.warning('请选择需要添加到的分类')
    return
  }
  if (selectedRows.value.length > 1) {
    ElMessage.warning('只能选择一项分类')
    return
  }
  visibleTitle.value = '添加分类代码'
  flag.value = true
  visible.value = true
  addfldmDiaForm.value.lbbm = nodeMessege.value.lbbm
}
// 摇号
const yaohaoBtn = () => {
  bydmService.yaohao({ lbbm: nodeMessege.value.lbbm }).then((res: any) => {
    addfldmDiaForm.value.dm = res.data.dm
  })
}
// 添加按钮确定弹框
const addfldmQdan = () => {
  if (!(addfldmDiaForm.value.dm && addfldmDiaForm.value.mc)) {
    ElMessage.warning('请完善信息')
    return
  }

  if (!(addfldmDiaForm.value.dm.length === 13)) {
    ElMessage.warning('代码只能输入13位')
    return
  }
  // flag 为true 为添加子代码
  // flag false  为添加代码
  if (flag.value) {
    addfldmDiaForm.value.fdm = tableNodeMessege.value.dm
  }

  bydmService.addDiaApi({ ...addfldmDiaForm.value }).then(() => {
    ElMessage.success('操作成功')
    queryTable()
    visible.value = false
    addfldmDiaForm.value = {
      dm: '',
      mc: '',
      lbbm: '',
      xh: '',
      sm: '',
      fdm: '',
    }
  })
}
// 关闭
const close = () => {
  flag.value = false
  addForm.value = {}
}
const close1 = () => {
  chanefldmDiaForm.value = {
    dm: '',
    mc: '',
    lbbm: '',
    xh: '',
    sm: '',
    fdm: '',
    fjdm: undefined,
  }
}
const close2 = () => {
  addfldmDiaForm.value = {
    dm: '',
    mc: '',
    lbbm: '',
    xh: '',
    sm: '',
    fdm: '',
  }
}
const flFilter = ref('')
const onSearch = (value: string) => {
  if (value) {
    const tree = JSON.parse(JSON.stringify(tableLists1.value))
    tableLists.value = filter1(tree, value)
  } else {
    tableLists.value = tableLists1.value
  }
}
const dmFilter = ref('')
const onChange = (value: string) => {
  if (value) {
    const tree = JSON.parse(JSON.stringify(gData1.value))
    gData.value = filter(tree, value)
  } else {
    gData.value = gData1.value
  }
}
// nodes就是树形的最原始数据，query就是关键字，最后会返回满足条件的节点数组
const filter = (nodes: any[], query: string) => {
  // 条件就是节点的title过滤关键字
  const predicate = (node: any) => pinyin.match(node.lbmc, query)
  if (!(nodes && nodes.length)) {
    return []
  }
  const newChildren = []
  for (const node of nodes) {
    // 以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
    // 1. 子孙节点中存在符合条件的，即 subs 数组中有值
    // 2. 自己本身符合条件
    const subs = filter(node.children, query)
    if (predicate(node)) {
      newChildren.push(node)
    } else if (subs && subs.length) {
      node.children = subs
      newChildren.push(node)
    }
  }
  return newChildren.length ? newChildren : []
}
// nodes就是树形的最原始数据，query就是关键字，最后会返回满足条件的节点数组
const filter1 = (nodes: any[], query: string) => {
  // 条件就是节点的title过滤关键字
  const predicate = (node: any) => pinyin.match(node.mc, query) || pinyin.match(node.sm, query)
  if (!(nodes && nodes.length)) {
    return []
  }
  const newChildren = []
  for (const node of nodes) {
    // 以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
    // 1. 子孙节点中存在符合条件的，即 subs 数组中有值
    // 2. 自己本身符合条件
    const subs = filter(node.children, query)
    if (predicate(node)) {
      newChildren.push(node)
    } else if (subs && subs.length) {
      node.children = subs
      newChildren.push(node)
    }
  }
  return newChildren.length ? newChildren : []
}
const bianJi = (item: any) => {
  bydmService.getFldm({ dm: item.dm }).then((res: any) => {
    chanefldmDiaForm.value = res.data
  })
  changefldmlbDia.value = true
}
const deletTable = (item: any) => {
  ElMessageBox.confirm('确定删除吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    bydmService
      .deletDiaApi({
        dm: item.dm,
      })
      .then(() => {
        ElMessage.success('删除成功')
        queryTable()
      })
  })
}
const changefldmQdan = () => {
  const data = {
    dm: chanefldmDiaForm.value.dm,
    fdm: chanefldmDiaForm.value.fdm,
    lbbm: chanefldmDiaForm.value.lbbm,
    mc: chanefldmDiaForm.value.mc,
    sm: chanefldmDiaForm.value.sm,
  }
  bydmService.changeDiaApi(data).then(() => {
    ElMessage.success('操作成功')
    changefldmlbDia.value = false
    chanefldmDiaForm.value = {
      dm: '',
      mc: '',
      lbbm: '',
      xh: '',
      sm: '',
      fdm: '',
      fjdm: undefined,
    }
    queryTable()
  })
}
const selectionChange = (rows: any[]) => {
  selectedRows.value = rows
  tableNodeMessege.value = rows[0]
}
serchMenuLeft()
</script>

<template>
  <div class="bydm-permission" v-loading="loading">
    <div class="bydm-left">
      <div class="card-container">
        <el-tabs model-value="1">
          <el-tab-pane name="1" label="分类代码类别">
            <div class="btn-group">
              <el-button
                link
                type="primary"
                icon="RefreshRight"
                @click="
                  () => {
                    serchMenuLeft()
                    ElMessage.success('刷新成功')
                  }
                "
              >
                刷新
              </el-button>
              <el-button link type="primary" icon="Plus" @click="addfldmlbBtn"> 添加 </el-button>
              <el-button link type="warning" icon="Edit" @click="onEdit"> 编辑 </el-button>
              <el-button link type="danger" icon="Delete" @click="delet"> 移除 </el-button>
            </div>
            <div class="bottom" style="margin-top: 20px; height: calc(100% - 32px)">
              <el-input
                v-model="dmFilter"
                suffix-icon="Search"
                style="margin-bottom: 8px"
                @input="onChange"
                clearable
              />
              <el-scrollbar max-height="calc(100vh - 480px)">
                <el-tree
                  style="width: 100%"
                  @node-click="treeSelect"
                  :current-node-key="selectTreeNode"
                  :data="gData"
                  :props="replaceFields"
                  check-on-click-node
                  :expand-on-click-node="false"
                  defaultExpandAll
                  node-key="lbbm"
                >
                  <template #default="{ node, data }">
                    <el-icon>
                      <Folder v-if="data.level === 1" />
                      <Document v-else-if="data.level === 2" />
                    </el-icon>
                    <span style="margin-left: 4px">{{ node.label }}</span>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="right">
      <div class="card-container">
        <el-tabs model-value="1">
          <el-tab-pane name="1" label="分类代码">
            <div style="height: 40px">
              <div style="float: left">
                <el-input
                  v-model="flFilter"
                  suffix-icon="Search"
                  style="width: 240px"
                  placeholder="名称或者说明查询"
                  @input="onSearch"
                />
              </div>
              <div style="float: right">
                <div class="btn-group">
                  <el-button link type="primary" icon="Plus" @click="add"> 添加 </el-button>
                  <el-button link type="primary" icon="Plus" @click="addChildDm">
                    添加子代码
                  </el-button>
                </div>
              </div>
            </div>

            <el-table
              :data="tableLists"
              row-key="key"
              @selection-change="selectionChange"
              max-height="calc(100vh - 420px)"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column
                v-for="column in columns"
                show-overflow-tooltip
                :key="column.dataIndex"
                :prop="column.dataIndex"
                :label="column.title"
              />
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="scope">
                  <el-button link type="primary" @click="bianJi(scope.row)"> 编辑 </el-button>
                  <el-button link type="danger" @click="deletTable(scope.row)"> 移除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 添加分类代码类别 -->
    <el-dialog
      v-model="addfldmlbDia"
      :title="fldmlbTitle"
      class="bydm"
      @close="close"
      align-center
      :close-on-click-modal="false"
    >
      <table class="riginalTable" style="table-layout: fixed" aria-describedby="bydm">
        <tr>
          <th style="width: 35%">
            类别名称
            <span class="red">*</span>
          </th>
          <th>
            <input class="riginalInput" v-model="addForm.lbmc" />
          </th>
        </tr>
        <tr>
          <td>
            类别编码
            <span class="red">（4位）*</span>
          </td>
          <td>
            <input
              class="riginalInput"
              :style="{
                cursor: fldmlbTitle == '修改分类代码类别' ? 'not-allowed' : '',
              }"
              v-model="addForm.lbbm"
              :disabled="fldmlbTitle == '修改分类代码类别'"
            />
          </td>
        </tr>
        <tr>
          <td>
            所属类别
            <span class="red">*</span>
          </td>
          <td>
            <input class="riginalInput" v-model="addForm.dmsslb" />
          </td>
        </tr>
        <tr>
          <td>类别标准</td>
          <td>
            <input class="riginalInput" v-model="addForm.lbbz" />
          </td>
        </tr>
        <tr>
          <td>类别国标代码</td>
          <td>
            <input class="riginalInput" v-model="addForm.lbgbdm" />
          </td>
        </tr>
      </table>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="addfldm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加分类代码2 -->
    <el-dialog
      v-model="visible"
      :title="visibleTitle"
      class="bydm"
      @close="close2"
      align-center
      :close-on-click-modal="false"
    >
      <table class="riginalTable" style="table-layout: fixed" aria-describedby="bydm">
        <tr>
          <th style="width: 25%">
            代码
            <span class="red">（13位）*</span>
          </th>
          <th>
            <input
              class="riginalInput"
              style="float: left; width: 80%"
              v-model="addfldmDiaForm.dm"
            />
            <span class="btn-item" style="float: right" @click="yaohaoBtn">要号</span>
          </th>
        </tr>
        <tr>
          <td>
            名称
            <span class="red">*</span>
          </td>
          <td>
            <input class="riginalInput" v-model="addfldmDiaForm.mc" />
          </td>
        </tr>
        <tr>
          <td>类别编码(<span class="red">4位</span>)</td>
          <td>
            <input
              class="riginalInput"
              v-model="addfldmDiaForm.lbbm"
              disabled
              style="cursor: not-allowed"
            />
          </td>
        </tr>
        <tr>
          <td>说明</td>
          <td>
            <el-input
              v-model="addfldmDiaForm.sm"
              type="textarea"
              style="border: none; resize: none"
            />
          </td>
        </tr>
      </table>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="addfldmQdan">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改分类代码 -->
    <el-dialog
      v-model="changefldmlbDia"
      title="修改分类代码"
      class="bydm"
      @close="close1"
      align-center
      :close-on-click-modal="false"
    >
      <table class="riginalTable" style="table-layout: fixed" aria-describedby="修改分类代码">
        <tr>
          <th style="width: 25%">
            代码
            <span class="red">（13位）*</span>
          </th>
          <th>
            <input
              class="riginalInput"
              v-model="chanefldmDiaForm.dm"
              disabled
              style="cursor: not-allowed"
            />
          </th>
        </tr>
        <tr>
          <td>
            名称
            <span class="red">*</span>
          </td>
          <td>
            <input class="riginalInput" v-model="chanefldmDiaForm.mc" />
          </td>
        </tr>
        <tr>
          <td>类别编码(<span class="red">4位</span>)</td>
          <td>
            <input
              class="riginalInput"
              v-model="chanefldmDiaForm.lbbm"
              disabled
              style="cursor: not-allowed"
            />
          </td>
        </tr>
        <tr>
          <td>说明</td>
          <td>
            <el-input
              v-model="chanefldmDiaForm.sm"
              type="textarea"
              style="border: none; resize: none"
            />
          </td>
        </tr>
      </table>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="changefldmQdan">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.bydm-permission {
  width: 100%;
  height: calc(100vh - 300px);
  background: #f0f2f5;
  display: flex;
  .card-container {
    border: 0 !important;
  }
  .bydm-left {
    min-width: 315px;
    max-width: 315px;
    height: 100%;
    margin-right: 12px;
    background-color: #fff;
    border: 1px solid #dcdcdc;
    .tab-box {
      padding: 10px;
    }
    .el-tree {
      margin-top: 8px;
      &:deep(.el-tree-node) {
        &.is-current {
          position: relative;
          .el-tree-node__content {
            background-color: #d3effc;
            color: #409eff;
            &:hover {
              background-color: #d3effc;
            }
          }
        }
        & > .el-tree-node__children {
          & > .el-tree-node.is-current {
            & > .el-tree-node__content {
              background-color: #d3effc;
              color: #409eff;
              &:hover {
                background-color: #d3effc;
              }
            }
          }
          & > .el-tree-node:not(.is-current) {
            & > .el-tree-node__content {
              color: #666;
              background-color: #fff;
            }
          }
        }
        .el-tree-node__content {
          height: 32px;
          color: #666;
          &:hover {
            background-color: #dcdcdc;
          }
        }
      }
    }
  }
  .right {
    float: right;
    height: 100%;
    width: calc(100% - 330px);
    background-color: #fff;
    border: 1px solid #dcdcdc;
  }
}
.card-container {
  .el-tabs {
    border: none;
  }
  :deep(.el-tabs__nav) {
    padding: 0 16px;
    .el-tabs__active-bar {
      background-color: #1890ff;
    }
    .is-active {
      color: #1890ff;
      font-size: 16px;
      font-weight: 700;
    }
  }
  :deep(.el-tab-pane) {
    padding: 0 16px 16px;
  }
  :deep(.el-collapse-item__header) {
    padding-left: 12px;
    color: #666;
    font-weight: bold;
    border-bottom: 1px solid #dcdcdc;
    &::before {
      content: '';
      height: 19px;
      border-left: 4px solid #0090ff;
      position: relative;
      left: -10px;
      top: 0;
    }
  }
  :deep(.el-collapse-item__content) {
    padding: 16px 0;
  }
}
</style>
